﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
using System.Web.Security;
using U9BJWebApi.CheckLogin;
using U9BJWebApi.Models;
//using UFIDA.U9.Cust.BJ.CreateCompleteRptSV;

namespace U9BJWebApi.Controllers
{
	public class SentController : ApiController
	{
		public static string connectionString = Decrypt(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString(), "ConnectionString");
		public static string ERPURL = System.Configuration.ConfigurationManager.AppSettings["ERPURL"].ToString();
		public static string enterpriseID = System.Configuration.ConfigurationManager.AppSettings["enterpriseID"].ToString();
		public static string TokenCheck = System.Configuration.ConfigurationManager.AppSettings["TokenCheck"].ToString();
		//public static string MESURL = System.Configuration.ConfigurationManager.AppSettings["MESURL"].ToString();

		[HttpPost]
		public Result<string> GetToken(TokenDTO it)
		{
			Result<string> rtn = new Result<string>();
			DataSet orgds = DbHelperSQL.Query(@"select id from Base_Organization where code = '" + it.Org + "' ");
			if (orgds != null && orgds.Tables.Count > 0)
			{
				var OrgID = Convert.ToInt64(orgds.Tables[0].Rows[0]["id"]);
				DataSet userds = DbHelperSQL.Query(@"select id from base_user where code = '" + it.UserNo + "' ");
				if (userds != null && userds.Tables.Count > 0)
				{
					var UserId = Convert.ToInt64(userds.Tables[0].Rows[0]["id"]);

					string url = ERPURL + "/U9/Services/UFIDA.CUST.HX.BM.BMSV.ICheckLoginSV.svc?wsdl";
					UFIDACUSTHXBMBMSVLoginInfoDTOData info = CheckLogin(OrgID, UserId, it.UserNo, it.UserPwd, url, enterpriseID);
					if (info == null || info.m_loginResult != "登陆成功")
					{

						rtn.msg = info.m_loginResult;
						rtn.code = 0;
						return rtn;
					}
					else
					{
						string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
						if (!string.IsNullOrEmpty(MESURL))
						{
							string tokenck = $"select Code  from Inter_MESToken where URL = '{MESURL}' and UserID = {UserId} and DisableDate > GetDate()";
							DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
							if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
							{
								rtn.data = Convert.ToString(tokends.Tables[0].Rows[0]["Code"]);
								rtn.msg = "Token获取成功";
								return rtn;
							}

							it.URL = MESURL;
							it.Date = DateTime.Now;

							string tokenstring = JsonConvert.SerializeObject(it);
							string token = MD5(tokenstring);//加密产生token,

							var tokensql = $@"INSERT INTO [dbo].[Inter_MESToken] ([ID], [CreatedOn], [ModifiedOn], [DisableDate], [CreatedBy], [ModifiedBy], [Code], [UserName], [URL], [SysVersion], [UserID]) 
														  VALUES ({GuidToLongID()}, '{DateTime.Now}', '{DateTime.Now}', '{DateTime.Now.AddMinutes(5)}', N'MES', N'MES', N'{token}', N'{it.UserNo}', '{MESURL}', 0,{UserId});";
							DbHelperSQL.ExecuteSql(tokensql, connectionString);

							rtn.data = token;
							rtn.msg = "Token获取成功 有效期5分钟";
							return rtn;
						}
						

					}
				}
			}

			rtn.code = 0;
			rtn.msg = "获取Token失败";
			return rtn;
		}

		/// <summary>
		/// 字符串MD5加密
		/// </summary>
		/// <param name="Text">要加密的字符串</param>
		/// <returns>密文</returns>
		public static string MD5(string Text)
		{
			byte[] buffer = System.Text.Encoding.Default.GetBytes(Text);
			try
			{
				System.Security.Cryptography.MD5CryptoServiceProvider check;
				check = new System.Security.Cryptography.MD5CryptoServiceProvider();
				byte[] somme = check.ComputeHash(buffer);
				string ret = "";
				foreach (byte a in somme)
				{
					if (a < 16)
						ret += "0" + a.ToString("X");
					else
						ret += a.ToString("X");
				}
				return ret.ToLower();
			}
			catch
			{
				throw;
			}
		}


		/// <summary>
		/// 检查登陆
		/// </summary>
		/// <returns></returns>
		public static UFIDACUSTHXBMBMSVLoginInfoDTOData CheckLogin(long orgID, long userId, string userCode, string passward, string url, string enterpriseID)
		{
			CheckLoginSVStub login = new CheckLoginSVStub();

			UFIDACUSTHXBMBMSVLoginInfoDTOData info = new UFIDACUSTHXBMBMSVLoginInfoDTOData();

			//传入URL、设定时间
			login.Url = url;
			//给上下文信息赋值
			//实例化上下文对象
			CheckLogin.ThreadContext context = CreateContext(orgID, userId, enterpriseID);

			//给出入参数赋值
			info.m_userCode = userCode;
			info.m_passward = passward;
			info.m_orgID = orgID.ToString();
			info.m_languageID = "1002006072100009";
			info.m_iP = "192.168.125.84";
			info.m_enterpriseId = enterpriseID;


			info = login.Do(context, info, out CheckLogin.MessageBase[] messageBase);
			return info;
		}

		/// <summary>
		/// 实例化上下文对象
		/// </summary>
		/// <returns></returns>
		public static CheckLogin.ThreadContext CreateContext(long orgID, long userId, string enterpriseID)
		{
			//实例化上下文对象
			CheckLogin.ThreadContext context = new CheckLogin.ThreadContext();

			CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[] av = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[7];

			av[0] = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
			av[0].Key = "OrgID";                        //组织
			av[0].Value = orgID;

			av[1] = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
			av[1].Key = "UserID";                       //用户
			av[1].Value = userId;

			av[2] = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
			av[2].Key = "CultureName";                  //语言
			av[2].Value = "zh-CN";

			av[3] = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
			av[3].Key = "EnterpriseID";                 //企业
			av[3].Value = enterpriseID;

			//av[4] = new ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
			//av[4].Key = "DefaultCultureName";           //默认语言
			//av[4].Value = PubClass.Culture;

			//av[5] = new ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
			//av[5].Key = "EnterpriseName";               //企业名称
			//av[5].Value = PubClass.EnterpriseName;

			//av[6] = new ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
			//av[6].Key = "Support_CultureNameList";      //语言
			//av[6].Value = PubClass.Culture;

			context.nameValueHas = av;

			return context;
		}
		public class TokenDTO
		{
			public string Org { get; set; }
			public string UserNo { get; set; }
			public string UserPwd { get; set; }
			public DateTime Date { get; set; }
			public string URL { get; set; }

		}

		[HttpPost]
		public Result<string> ItemmasterToMes(ItemmasterToMesDTO it)
		{
			WriteLog("进入料品接口", "HLMessge");
			Result<string> result = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						result.code = 0;
						result.msg = "该token已失效";
						return result;
					}
				}
				else
				{
					result.code = 0;
					result.msg = "无效token";
					return result;
				}
			}
			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			if (string.IsNullOrEmpty(MESURL))
			{
				result.code = 0;
				result.msg = "未找到MES地址";
				return result;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'ItemmasterToMes', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);
			string sql = String.Empty;
			//if (it.Org == "2574")
			//{
			//	sql = $@"select a.*,op.name ManagerId,c.name UOMName,dl.name MainItemCategoryName,el.name AssetCategoryName ,a1.DescFlexField_PrivateDescSeg19 客户编码,a1. DescFlexField_PrivateDescSeg17 客户描述 ,
			//								dvt.name 车型,a1.DescFlexField_PrivateDescSeg14 [3C型号],a1.DescFlexField_PrivateDescSeg18 MES描述
			//								from Inter_ItemMasterBE a
			//								left join CBO_Itemmaster a1 on a1.Code = a.Code
			//								left join CBO_InventoryInfo a2 on a2.ItemMaster = a1.id
			//								left join CBO_Operators_Trl op on op.id = a2.WarehouseManager
			//								left join Base_Organization org on org.id = a1.org 
			//								left join Base_UOM b on b.Code = a.UOM 
			//								left join Base_UOM_trl C on b.id = c.id 
			//								left join CBO_Category d on d.code = a.MainItemCategory
			//								left join CBO_Category_trl dl on d.id = dl.id
			//								left join CBO_Category e on e.code = a.AssetCategory
			//								left join CBO_Category_trl el on e.id = el.id
			//								left join Base_DefineValue dv on dv.code = a1.DescFlexField_PrivateDescSeg10
			//								left join Base_ValueSetDef vsd on vsd.id = dv.ValueSetDef  and vsd.Code = 'Z006'
			//								left join Base_DefineValue_Trl dvt on dvt.id = dv.id
			//								where org.code = a.OrgCode and  (a.status = 0 ) and  '{it.Org}' like '%'+a.OrgCode+'%'  and   vsd.id  is not null";

			//}
			//else
			//{

			//	sql = $@"select a.*,op.name ManagerId,c.name UOMName,dl.name MainItemCategoryName,el.name AssetCategoryName ,a1.DescFlexField_PrivateDescSeg19 客户编码,a1. DescFlexField_PrivateDescSeg17 客户描述 ,
			//								a1.DescFlexField_PrivateDescSeg14 [3C型号],a1.DescFlexField_PrivateDescSeg18 MES描述
			//								from Inter_ItemMasterBE a
			//								left join CBO_Itemmaster a1 on a1.Code = a.Code
			//								left join CBO_InventoryInfo a2 on a2.ItemMaster = a1.id
			//								left join CBO_Operators_Trl op on op.id = a2.WarehouseManager
			//								left join Base_Organization org on org.id = a1.org 
			//								left join Base_UOM b on b.Code = a.UOM 
			//								left join Base_UOM_trl C on b.id = c.id 
			//								left join CBO_Category d on d.code = a.MainItemCategory
			//								left join CBO_Category_trl dl on d.id = dl.id
			//								left join CBO_Category e on e.code = a.AssetCategory
			//								left join CBO_Category_trl el on e.id = el.id

			//								where org.code = a.OrgCode and  (a.status = 0 ) and  '{it.Org}' like '%'+a.OrgCode+'%'  ";

			//}

			sql = $@"select DISTINCT a.*,op.name ManagerId,c.name UOMName,dl.name MainItemCategoryName,el.name AssetCategoryName ,a1.DescFlexField_PrivateDescSeg19 客户编码,a1. DescFlexField_PrivateDescSeg17 客户描述 ,
											cx.name 车型,a1.DescFlexField_PrivateDescSeg14 [3C型号],a1.DescFlexField_PrivateDescSeg18 MES描述,a1.DescFlexField_PrivateDescSeg7 业务单据不可用
											from Inter_ItemMasterBE a
											left join CBO_Itemmaster a1 on a1.Code = a.Code
											left join CBO_InventoryInfo a2 on a2.ItemMaster = a1.id
											left join CBO_Operators_Trl op on op.id = a2.WarehouseManager
											left join Base_Organization org on org.id = a1.org 
											left join Base_UOM b on b.Code = a.UOM 
											left join Base_UOM_trl C on b.id = c.id 
											left join CBO_Category d on d.code = a.MainItemCategory
											left join CBO_Category_trl dl on d.id = dl.id
											left join CBO_Category e on e.code = a.AssetCategory
											left join CBO_Category_trl el on e.id = el.id
											left join (select a.Code,c.Name from Base_DefineValue a
											inner join Base_DefineValue_Trl c on a.id=c.id
											inner join Base_ValueSetDef b on a.ValueSetDef=b.ID
											where b.Code='Z006')cx on cx.Code=a1.DescFlexField_PrivateDescSeg10
											where org.code = a.OrgCode and  (a.status = 0 ) and  '{it.Org}' like '%'+a.OrgCode+'%'  ";
			DataSet ds = DbHelperSQL.Query(sql, connectionString);

			List<ItemMasterDTO> ItemMasterDTOs = new List<ItemMasterDTO>();

			//var ids = "";
			if (ds.Tables.Count > 0)
			{
				DataTable dt = ds.Tables[0];
				if (dt != null && dt.Rows.Count > 0)
				{
					for (int i = 0; i < dt.Rows.Count; i++)
					{
						var ProductTypeId = "";
						switch (dt.Rows[i]["ItemFormAttribute"].ToString())
						{
							case "10":
								ProductTypeId = "FERT";
								break;
							case "9":
								ProductTypeId = "ROH";
								break;
							default:
								ProductTypeId = "FERT";
								break;
						}	

						ItemMasterDTO itemMasterDTO = new ItemMasterDTO();
						itemMasterDTO.FactoryId = dt.Rows[i]["OrgCode"].ToString();
						itemMasterDTO.MaterielId = dt.Rows[i]["Code"].ToString();
						itemMasterDTO.MaterieName = dt.Rows[i]["Name"].ToString();
						itemMasterDTO.Mnemonic = dt.Rows[i]["Name"].ToString();
						itemMasterDTO.Spec = dt.Rows[i]["SPECS"].ToString();
						itemMasterDTO.MetricId = dt.Rows[i]["Uom"].ToString();
						itemMasterDTO.MetricName = dt.Rows[i]["UOMName"].ToString();
						//itemMasterDTO.MetricName = dt.Rows[i]["UomName"].ToString();
						itemMasterDTO.StoreRoomId = dt.Rows[i]["WhCode"].ToString();
						itemMasterDTO.ManagerId = dt.Rows[i]["ManagerId"].ToString();
						//itemMasterDTO.Begindate = Convert.ToDateTime(dt.Rows[i]["EffectiveDate"].ToString());
						//itemMasterDTO.Enddate = Convert.ToDateTime(dt.Rows[i]["DisableDate"].ToString());
						//itemMasterDTO.IsValid = dt.Rows[i]["IsValid"].ToString();
						itemMasterDTO.ProductTypeId = string.IsNullOrEmpty(dt.Rows[i]["MainItemCategory"].ToString())? ProductTypeId : dt.Rows[i]["MainItemCategory"].ToString();
						itemMasterDTO.ProductTypeNames = dt.Rows[i]["MainItemCategoryName"].ToString();
						itemMasterDTO.CreateMan = dt.Rows[i]["CreatedBy"].ToString();
						itemMasterDTO.CreateDate = Convert.ToDateTime(dt.Rows[i]["CreatedOn"].ToString());
						itemMasterDTO.ItemFormAttribute = dt.Rows[i]["ItemFormAttribute"].ToString();
						itemMasterDTO.MaterielGroupId = dt.Rows[i]["AssetCategory"].ToString();
						itemMasterDTO.MaterielGroupName = dt.Rows[i]["AssetCategoryName"].ToString();
						itemMasterDTO.ERPPkid = Convert.ToInt64(dt.Rows[i]["id"].ToString());
						itemMasterDTO.PubStr1 = dt.Rows[i]["客户编码"].ToString();
						itemMasterDTO.PubStr2 = dt.Rows[i]["客户描述"].ToString();
						//if (it.Org == "2574")
						//{
						itemMasterDTO.PubStr3 = dt.Rows[i]["车型"].ToString();
						//}
						itemMasterDTO.PubStr4 = dt.Rows[i]["3C型号"].ToString();
						itemMasterDTO.PubStr5 = dt.Rows[i]["MES描述"].ToString();
						itemMasterDTO.PubInt1 = Convert.ToBoolean(dt.Rows[i]["业务单据不可用"]) == true ?1 : 0;
						ItemMasterDTOs.Add(itemMasterDTO);

						//ids += dt.Rows[i]["id"].ToString() + ",";
					}

				}
			}
			if (ItemMasterDTOs.Count > 0)
			{
				int a = Convert.ToInt32(Math.Floor(Convert.ToDecimal(ItemMasterDTOs.Count / 10)));
				var b = ItemMasterDTOs.Count - a*10;
				for (var i = 0; i < a; i++)
				{
					var Pkid = GuidToLongID();
					JobMsgDTO<ItemMasterDTO> Dto = new JobMsgDTO<ItemMasterDTO>();
					Dto.ERPPkid = Pkid;
					Dto.JobMsg = ItemMasterDTOs.GetRange(i*10,10);

					var idlist = Dto.JobMsg.Select(m => m.ERPPkid).ToArray();
					var ids = String.Join(",", idlist);
					SuccessRtn rtn = new SuccessRtn { rtnSuccess = false, rtnMsg = "未成功发送" };


					if (it.Org != "2573")
					{

						List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
						QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
						//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
						QuartzTaskInfoDTO.jobId = "U9_MES_MATERIELINFO";
						QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(Dto);
						QuartzTaskInfoDTO.quartzStatus = 0;
						QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
						string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
						{
							factoryId = it.Org,
							userNo = "100",
							quartzTaskInfoDTOs = QuartzTaskInfoDTOs

						});
						//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
						rtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);
					}
					else
					{
						 rtn = PostHelper.HttpPosts(MESURL + "/api/P_materiel/PostBomData", JsonConvert.SerializeObject(Dto));
					}
					
					if (ids != "")
					{
						if (rtn.rtnSuccess)
						{
							DbHelperSQL.ExecuteSql("update Inter_ItemMasterBE set Status = 1,ERPPkid = " + Pkid + "  where id in (" + ids + ")", connectionString);
						}
						else
						{
							var Rdfalsesql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = Message +'错误信息:{rtn.rtnMsg}' where id ={rdid}";
							DbHelperSQL.ExecuteSql(Rdfalsesql, connectionString);
							DbHelperSQL.ExecuteSql("update Inter_ItemMasterBE set ERPPkid = " + Pkid + "  where id in (" + ids + ")", connectionString);
						}

					}

				}

				if (b > 0) 
				{
					var Pkid = GuidToLongID();
					JobMsgDTO<ItemMasterDTO> Dto = new JobMsgDTO<ItemMasterDTO>();
					Dto.ERPPkid = Pkid;
					Dto.JobMsg = ItemMasterDTOs.GetRange(a * 10, b);
					var idlist = Dto.JobMsg.Select(m => m.ERPPkid).ToArray();
					var ids = String.Join(",", idlist);
					SuccessRtn rtn = new SuccessRtn { rtnSuccess = false ,rtnMsg  = "未成功发送" };
					if (it.Org != "2573")
					{
						List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
						QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
						//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
						QuartzTaskInfoDTO.jobId = "U9_MES_MATERIELINFO";
						QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(Dto);
						QuartzTaskInfoDTO.quartzStatus = 0;
						QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
						string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
						{
							factoryId = it.Org,
							userNo = "100",
							quartzTaskInfoDTOs = QuartzTaskInfoDTOs

						});
						var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{IsnJson}' where id ={rdid}";
						DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
						//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
						rtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);
					}
					else
					{
					    rtn = PostHelper.HttpPosts(MESURL + "/api/P_materiel/PostBomData", JsonConvert.SerializeObject(Dto));						
					}
					if (ids != "")
					{
						if (rtn.rtnSuccess)
						{
							DbHelperSQL.ExecuteSql("update Inter_ItemMasterBE set Status = 1,ERPPkid = " + Pkid + "  where id in (" + ids + ")", connectionString);
						}
						else
						{
							var Rdfalsesql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = Message +'错误信息:{rtn.rtnMsg}' where id ={rdid}";
							DbHelperSQL.ExecuteSql(Rdfalsesql, connectionString);
							DbHelperSQL.ExecuteSql("update Inter_ItemMasterBE set ERPPkid = " + Pkid + "  where id in (" + ids + ")", connectionString);
						}
					}
				}
			}
			result.msg = "下发成功";
			return result;
		}

		public class ItemmasterToMesDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";

		}

		[HttpPost]
		public Result<string> BOMToMes(BOMSentDTO it)
		{
			Result<string> result = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						result.code = 0;
						result.msg = "该token已失效";
						return result;
					}
				}
				else
				{
					result.code = 0;
					result.msg = "无效token";
					return result;
				}
			}
			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			if (string.IsNullOrEmpty(MESURL))
			{
				result.code = 0;
				result.msg = "未找到MES地址";
				return result;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'BOMToMes', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);

			//DataSet ds = DbHelperSQL.Query($@"select bom.DescFlexField_PrivateDescSeg2 IsExpand,c.CreatedBy,c.CreatedOn,OrgCode,m.itemmaster ,m.BOMVersionCode,m.ProductUOM,m.EffectiveDate,m.DisableDate,c.Sequence,c.ItemMaster as ChildItemMaster,m.EffectiveDate as ChildEffectiveDate,m.DisableDate as ChildDisableDate,c.TradeMark,c.UsageQty,c.id
			//									from Inter_BOMMasterBE m
			//									left join Inter_BOMComponentBE c on m.id = c.Inter_BOMMasterBE
			//									left join CBO_BOMMaster bom on bom.ID = m.BOMMaster
			//									where (c.status = 0 ) and  '{it.Org}' like '%'+m.OrgCode+'%'", connectionString);

			List<BOMDTO> BOMDTOs = new List<BOMDTO>();
			string sql = $@"select bom.DescFlexField_PrivateDescSeg2 IsExpand,c.CreatedBy,c.CreatedOn,OrgCode,m.itemmaster ,m.BOMVersionCode,m.ProductUOM,m.EffectiveDate,m.DisableDate,c.Sequence,c.ItemMaster as ChildItemMaster,m.EffectiveDate as ChildEffectiveDate,m.DisableDate as ChildDisableDate,c.TradeMark,c.UsageQty,c.id
												from Inter_BOMMasterBE m
												left join Inter_BOMComponentBE c on m.id = c.Inter_BOMMasterBE
												left join CBO_BOMMaster bom on bom.ID = m.BOMMaster
												where (c.status = 0 ) and  '{it.Org}' like '%'+m.OrgCode+'%'";
			
			DataSet ds = DbHelperSQL.Query(sql, connectionString);
			//var ids = "";
			if (ds.Tables.Count > 0)
			{
				DataTable dt = ds.Tables[0];
				if (dt != null && dt.Rows.Count > 0)
				{
					for (int i = 0; i < dt.Rows.Count; i++)
					{


						BOMDTO BOMDTO = new BOMDTO();
						BOMDTO.FactoryId = dt.Rows[i]["OrgCode"].ToString();
						BOMDTO.MaterielId = dt.Rows[i]["ItemMaster"].ToString();
						BOMDTO.CopyRight = dt.Rows[i]["BOMVersionCode"].ToString();
						//BOMDTO.BOMType = holder.;
						BOMDTO.ProductUOM = dt.Rows[i]["ProductUOM"].ToString();
						BOMDTO.BeginDate = Convert.ToDateTime(dt.Rows[i]["EffectiveDate"].ToString());
						BOMDTO.EndDate = Convert.ToDateTime(dt.Rows[i]["DisableDate"].ToString());
						BOMDTO.CreateMan = dt.Rows[i]["CreatedBy"].ToString();
						BOMDTO.CreateDate = Convert.ToDateTime(dt.Rows[i]["CreatedOn"].ToString());
						BOMDTO.PubInt1 = string.IsNullOrEmpty(dt.Rows[i]["IsExpand"].ToString())?0: Convert.ToBoolean(dt.Rows[i]["IsExpand"]) ? 1 : 0;
						BOMDTO.ERPPkid = dt.Rows[i]["id"].ToString();
						List<BOMChild> bcs = new List<BOMChild>();
						BOMChild bc = new BOMChild();
						bc.CreateMan = dt.Rows[i]["CreatedBy"].ToString();
						bc.CreateDate = Convert.ToDateTime(dt.Rows[i]["CreatedOn"].ToString());
						bc.Sequence = Convert.ToInt32(dt.Rows[i]["Sequence"].ToString());
						bc.ChildMaterielId = dt.Rows[i]["ChildItemMaster"].ToString();
						//bc.ChildMaterielName = holder.ItemMaster.Name;
						bc.ChildBeginDate = Convert.ToDateTime(dt.Rows[i]["ChildEffectiveDate"].ToString());
						bc.ChildEndDate = Convert.ToDateTime(dt.Rows[i]["ChildDisableDate"].ToString());
						bc.ProviderId = dt.Rows[i]["TradeMark"].ToString();
						bc.Qty = Convert.ToDecimal(dt.Rows[i]["UsageQty"].ToString());
						//bc.IsVaild = holder.IsEffective ? "Y" : "N";
						bcs.Add(bc);
						BOMDTO.BOMChilds = bcs;

						BOMDTOs.Add(BOMDTO);

						//ids += dt.Rows[i]["id"].ToString() + ",";
					}

				}
			}

			var bomsgroupbymaster = BOMDTOs.GroupBy(m => new { m.FactoryId, m.MaterielId, m.CopyRight }).ToList();
			List<BOMDTO> RTBOMDTOs = new List<BOMDTO>();
			foreach (var dtos in bomsgroupbymaster)
			{
				BOMDTO BOMDTO = new BOMDTO();
				BOMDTO.FactoryId = dtos.FirstOrDefault().FactoryId;
				BOMDTO.MaterielId = dtos.FirstOrDefault().MaterielId;
				BOMDTO.CopyRight = dtos.FirstOrDefault().CopyRight;
				//BOMDTO.BOMType = holder.;
				BOMDTO.ProductUOM = dtos.FirstOrDefault().ProductUOM;
				BOMDTO.BeginDate = dtos.FirstOrDefault().BeginDate;
				BOMDTO.EndDate = dtos.FirstOrDefault().EndDate;
				BOMDTO.CreateMan = dtos.FirstOrDefault().CreateMan;
				BOMDTO.CreateDate = dtos.FirstOrDefault().CreateDate;
				BOMDTO.PubInt1 = dtos.FirstOrDefault().PubInt1;

				var idlist = dtos.Select(m => m.ERPPkid).ToArray();
				var ids = String.Join(",", idlist);

				BOMDTO.ERPPkid = ids;
				List<BOMChild> bcs = new List<BOMChild>();
				foreach (var dto in dtos)
				{
					if (bcs.FirstOrDefault(m => m.ChildMaterielId == dto.BOMChilds[0].ChildMaterielId) == null)
					{
						bcs.AddRange(dto.BOMChilds);
					}
				}
				BOMDTO.BOMChilds = bcs;
				RTBOMDTOs.Add(BOMDTO);
			}


			int a = Convert.ToInt32(Math.Floor(Convert.ToDecimal(RTBOMDTOs.Count / 5)));
			var b = RTBOMDTOs.Count - a * 5;
			for (var i = 0; i < a; i++)
			{
				var Pkid = GuidToLongID();
				JobMsgDTO<BOMDTO> Dto = new JobMsgDTO<BOMDTO>();
				Dto.ERPPkid = Pkid;
				Dto.JobMsg = RTBOMDTOs.GetRange(i * 5, 5); ;

				var idlist = Dto.JobMsg.Select(m => m.ERPPkid).ToArray();
				var ids = String.Join(",", idlist);
				SuccessRtn rtn = new SuccessRtn { rtnSuccess = false, rtnMsg = "未成功发送" };


				if (it.Org != "2573")
				{
					List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
					QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
					//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
					QuartzTaskInfoDTO.jobId = "U9_MES_BOM";
					QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(Dto);
					QuartzTaskInfoDTO.quartzStatus = 0;
					QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
					string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
					{
						factoryId = it.Org,
						userNo = "100",
						quartzTaskInfoDTOs = QuartzTaskInfoDTOs

					});
					var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{IsnJson}' where id ={rdid}";
					DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
					//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
					rtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);


				}
				else
				{
					rtn = PostHelper.HttpPosts(MESURL + "/api/P_bom_main/PostBomData", JsonConvert.SerializeObject(Dto));
				}
				if (ids != "")
				{
					if (rtn.rtnSuccess)
					{
						DbHelperSQL.ExecuteSql("update Inter_BOMComponentBE set Status = 1,ERPPkid = " + Pkid + " where  id in (" + ids + ")", connectionString);
					}
					else
					{
						var Rdfalsesql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = Message +'错误信息:{rtn.rtnMsg}' where id ={rdid}";
						DbHelperSQL.ExecuteSql(Rdfalsesql, connectionString);
						DbHelperSQL.ExecuteSql("update Inter_BOMComponentBE set ERPPkid = " + Pkid + " where  id in (" + ids + ")", connectionString);
					}


				}
			}
			if (b > 0)
			{
				var Pkid = GuidToLongID();
				JobMsgDTO<BOMDTO> Dto = new JobMsgDTO<BOMDTO>();
				Dto.ERPPkid = Pkid;
				Dto.JobMsg = RTBOMDTOs.GetRange(a * 5, b);

				var idlist = Dto.JobMsg.Select(m => m.ERPPkid).ToArray();
				var ids = String.Join(",", idlist);
				SuccessRtn rtn = new SuccessRtn { rtnSuccess = false, rtnMsg = "未成功发送" };


				if (it.Org != "2573")
				{
					List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
					QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
					//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
					QuartzTaskInfoDTO.jobId = "U9_MES_BOM";
					QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(Dto);
					QuartzTaskInfoDTO.quartzStatus = 0;
					QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
					string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
					{
						factoryId = it.Org,
						userNo = "100",
						quartzTaskInfoDTOs = QuartzTaskInfoDTOs

					});
					//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
					var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{IsnJson}' where id ={rdid}";
					DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
					rtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);

				}
				else
				{
					rtn = PostHelper.HttpPosts(MESURL + "/api/P_bom_main/PostBomData", JsonConvert.SerializeObject(Dto));
				}
				if (ids != "")
				{
					if (rtn.rtnSuccess)
					{
						DbHelperSQL.ExecuteSql("update Inter_BOMComponentBE set Status = 1,ERPPkid = " + Pkid + " where  id in (" + ids + ")", connectionString);
					}
					else
					{
						var Rdfalsesql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = Message +'错误信息:{rtn.rtnMsg}' where id ={rdid}";
						DbHelperSQL.ExecuteSql(Rdfalsesql, connectionString);
						DbHelperSQL.ExecuteSql("update Inter_BOMComponentBE set ERPPkid = " + Pkid + " where  id in (" + ids + ")", connectionString);
					}



				}

			}
			result.msg = "下发成功";
			return result;
		}


		public class BOMSentDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";
		}


		[HttpPost]
		public Result<string> MOToMes(MOSentDTO it)
		{
			Result<string> result = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						result.code = 0;
						result.msg = "该token已失效";
						return result;
					}
				}
				else
				{
					result.code = 0;
					result.msg = "无效token";
					return result;
				}
			}
			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			if (string.IsNullOrEmpty(MESURL))
			{
				result.code = 0;
				result.msg = "未找到MES地址";
				return result;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'MOToMes', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);

			//单件分开发送
			DataSet ds = DbHelperSQL.Query($@"select mbv.VersionCode,m.id,m.CreatedBy,m.OrgCode,m.MO, m.ItemMaster,m.ProductQty,m.DemandDate,m.StartDate,m.CompleteDate,
											m.CompleteWh,m.BOMMaster,m.ProductUOM,l.ItemMaster as ChildItemMaster ,isnull(l.ActualReqQty,0) ActualReqQty,
											m.Task TJID,m.SysVersion version,dvt.Name  TeamId,mo.DescFlexField_PrivateDescSeg8 LineId,it.code1 CustomerMaterielId,
											case when mo.DescFlexField_PrivateDescSeg1 in ('10','30','50') then 'A' when  mo.DescFlexField_PrivateDescSeg1 in ('20','40','60') then  'B' else '' End ClassId
											from Inter_MOBE m
											left join Base_Organization org on org.code = m.orgcode
											left join MO_MO mo on mo.DocNo = m.mo and mo.org = org.id
											left join CBO_BOMVersion mbv on mbv.id = mo.BOMVersion
											left join MO_MOPickList l on l.mo = mo.id
											left join cbo_itemmaster it on it.id = mo.itemmaster
											left join Base_DefineValue dv on dv.Code = mo.DescFlexField_PrivateDescSeg7 
											left join Base_ValueSetDef vsd on vsd.id = dv.ValueSetDef  and vsd.Code = 'Z010'
											left join Base_DefineValue_Trl dvt on dvt.id = dv.id
											where (m.Status = 0 )  and  '{it.Org}' like '%'+m.OrgCode+'%'  and vsd.id is not null ", connectionString);

			List<MODTO> MODTOs = new List<MODTO>();

		
			if (ds.Tables.Count > 0)
			{
				DataTable dt = ds.Tables[0];
				if (dt != null && dt.Rows.Count > 0)
				{
					for (int i = 0; i < dt.Rows.Count; i++)
					{
						MODTO MODTO = new MODTO();
						MODTO.CreateMan = dt.Rows[i]["CreatedBy"].ToString();
						MODTO.FactoryId = dt.Rows[i]["OrgCode"].ToString();
						MODTO.Billno = dt.Rows[i]["MO"].ToString();
						//MODTO.CustomerId = 
						//MODTO.SrcBillNo = holder.MO.SrcDoc.SrcDocNo;
						//MODTO.Sequence = 
						MODTO.MaterielId = dt.Rows[i]["ItemMaster"].ToString();
						MODTO.CustomerMaterielId = dt.Rows[i]["CustomerMaterielId"].ToString();
						MODTO.PlanQty = Convert.ToDecimal(dt.Rows[i]["ProductQty"].ToString());
						MODTO.LineId = dt.Rows[i]["LineId"].ToString();
						MODTO.RequireDate = Convert.ToDateTime(dt.Rows[i]["CompleteDate"].ToString());
						MODTO.BeginDate = Convert.ToDateTime(dt.Rows[i]["StartDate"].ToString());
						MODTO.EndDate = Convert.ToDateTime(dt.Rows[i]["CompleteDate"].ToString());
						MODTO.StoreRoomId = dt.Rows[i]["CompleteWh"].ToString(); 
						MODTO.BomId = dt.Rows[i]["BOMMaster"].ToString();
						MODTO.MetricId = dt.Rows[i]["ProductUOM"].ToString();
						MODTO.PubStr1 = dt.Rows[i]["TJID"].ToString();
						MODTO.ERPPkid = Convert.ToInt64(dt.Rows[i]["id"].ToString()); ;
						MODTO.Version = Convert.ToInt32(dt.Rows[i]["version"]);
						MODTO.TeamId = dt.Rows[i]["TeamId"].ToString();
						MODTO.ClassId = dt.Rows[i]["ClassId"].ToString();
						MODTO.BomVersion = dt.Rows[i]["VersionCode"].ToString();
						List<MOPickListDTO> mpls = new List<MOPickListDTO>();
						MOPickListDTO mpl = new MOPickListDTO();
						mpl.MaterielId = dt.Rows[i]["ChildItemMaster"].ToString();
						mpl.ActualReqQty = Convert.ToDecimal(dt.Rows[i]["ActualReqQty"]);
						mpls.Add(mpl);

						MODTO.MOPickLists = mpls;


						MODTOs.Add(MODTO);

						//if (!ids.Contains(dt.Rows[i]["id"].ToString()))
						//{
						//	ids += dt.Rows[i]["id"].ToString() + ",";
						//}
		
					}

				}
			}


			var MOListgroupbymaster = MODTOs.GroupBy(m => new { m.FactoryId, m.MaterielId,m.Billno,m.ERPPkid }).ToList();
			List<MODTO> RTMODTOs = new List<MODTO>();
			foreach (var dtos in MOListgroupbymaster)
			{
				MODTO MODTO = new MODTO();
				MODTO.CreateMan = dtos.FirstOrDefault().CreateMan;
				MODTO.FactoryId = dtos.FirstOrDefault().FactoryId;
				MODTO.Billno = dtos.FirstOrDefault().Billno;
				//MODTO.CustomerId = 
				//MODTO.SrcBillNo = holder.MO.SrcDoc.SrcDocNo;
				//MODTO.Sequence = 
				MODTO.MaterielId = dtos.FirstOrDefault().MaterielId;
				MODTO.CustomerMaterielId = dtos.FirstOrDefault().CustomerMaterielId;
				MODTO.PlanQty = dtos.FirstOrDefault().PlanQty;
				MODTO.LineId = dtos.FirstOrDefault().LineId;
				MODTO.RequireDate = dtos.FirstOrDefault().RequireDate;
				MODTO.BeginDate = dtos.FirstOrDefault().BeginDate;
				MODTO.EndDate = dtos.FirstOrDefault().EndDate;
				MODTO.StoreRoomId = dtos.FirstOrDefault().StoreRoomId;
				MODTO.BomId = dtos.FirstOrDefault().BomId;
				MODTO.MetricId = dtos.FirstOrDefault().MetricId;
				MODTO.PubStr1 = dtos.FirstOrDefault().PubStr1;
				MODTO.ERPPkid = dtos.FirstOrDefault().ERPPkid;
				MODTO.Version = dtos.FirstOrDefault().Version;
				MODTO.TeamId = dtos.FirstOrDefault().TeamId;
				MODTO.ClassId = dtos.FirstOrDefault().ClassId;
				MODTO.BomVersion = dtos.FirstOrDefault().BomVersion;
				List<MOPickListDTO> mpls = new List<MOPickListDTO>();
				foreach (var dto in dtos)
				{
					mpls.AddRange(dto.MOPickLists);
				}


				MODTO.MOPickLists = mpls;
				RTMODTOs.Add(MODTO);
			}

			//按套件ID分组
			var RTMODTOGroupByTask = RTMODTOs.GroupBy(m => m.PubStr1);



			foreach (var rtMODTOs in RTMODTOGroupByTask)
			{
				//task为空是单件  单独传
				if (rtMODTOs.FirstOrDefault().PubStr1 == "")
				{
					foreach (var rtMODTO in rtMODTOs)
					{
						var Pkid = GuidToLongID();
						JobMsgDTO<MODTO> Dto = new JobMsgDTO<MODTO>();
						Dto.ERPPkid = Pkid;
						Dto.JobMsg = new List<MODTO> { rtMODTO };


						var rt = DbHelperSQL.ExecuteSql("update Inter_MOBE set  SysVersion = " + (rtMODTO.Version + 1) + " where id = " + rtMODTO.ERPPkid + " and SysVersion = " + rtMODTO.Version, connectionString);
						if (rt == 0)
						{
							continue;
						}

						List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
						QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
						//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
						QuartzTaskInfoDTO.jobId = "U9_MES_MO";
						QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(Dto);
						QuartzTaskInfoDTO.quartzStatus = 0;
						QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
						string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
						{
							factoryId = it.Org,
							userNo = "100",
							quartzTaskInfoDTOs = QuartzTaskInfoDTOs

						});
						//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
						var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{IsnJson}' where id ={rdid}";
						DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
						var rtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);

						if (rtn.rtnSuccess)
						{
							DbHelperSQL.ExecuteSql("update Inter_MOBE set Status = 1,ERPPkid = " + Pkid + " where id  = " + rtMODTO.ERPPkid, connectionString);
						}
						else
						{
							var Rdfalsesql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = Message +'错误信息:{rtn.rtnMsg}' where id ={rdid}";
							DbHelperSQL.ExecuteSql(Rdfalsesql, connectionString);
							DbHelperSQL.ExecuteSql("update Inter_MOBE set Status = 2,ERPPkid = " + Pkid + " where id  = " + rtMODTO.ERPPkid, connectionString);
						}
					}
				}
				else    //task不为空是套件件  整个套件一起传
				{
					var Pkid = GuidToLongID();
					JobMsgDTO<MODTO> Dto = new JobMsgDTO<MODTO>();
					Dto.ERPPkid = Pkid;
					Dto.JobMsg = rtMODTOs.ToList();
					var idlist = Dto.JobMsg.Select(m => m.ERPPkid).ToArray();
					var ids = String.Join(",", idlist);

					var rt = DbHelperSQL.ExecuteSql("update Inter_MOBE set  SysVersion = " + (rtMODTOs.FirstOrDefault().Version + 1) + " where id in (" + ids + ") and SysVersion = " + rtMODTOs.FirstOrDefault().Version, connectionString);
					if (rt == 0)
					{
						continue;
					}

					List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
					QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
					//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
					QuartzTaskInfoDTO.jobId = "U9_MES_MO";
					QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(Dto);
					QuartzTaskInfoDTO.quartzStatus = 0;
					QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
					string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
					{
						factoryId = it.Org,
						userNo = "100",
						quartzTaskInfoDTOs = QuartzTaskInfoDTOs

					});
					//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
					var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{IsnJson}' where id ={rdid}";
					DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
					var rtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);

					if (rtn.rtnSuccess)
					{
						DbHelperSQL.ExecuteSql("update Inter_MOBE set Status = 1,ERPPkid = " + Pkid + " where id in (" + ids + ")", connectionString);
					}
					else
					{
						DbHelperSQL.ExecuteSql("update Inter_MOBE set Status = 2,ERPPkid = " + Pkid + " where id in (" + ids + ")", connectionString);
					}
				}

			}


			result.msg = "下发成功";
			return result;
		}


		public class MOSentDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";
		}

		[HttpPost]
		public Result<string> CreatePullListCallBack(CreatePullListCallBackDTO it)
		{
			Result<string> result = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						result.code = 0;
						result.msg = "该token已失效";
						return result;
					}
				}
				else
				{
					result.code = 0;
					result.msg = "无效token";
					return result;
				}
			}
			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			if (string.IsNullOrEmpty(MESURL))
			{
				result.code = 0;
				result.msg = "未找到MES地址";
				return result;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'CreatePullListCallBack', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);

			DataSet ds = DbHelperSQL.Query($"select * from Inter_PullListBE where (Status = 1 or status = 2)  and   '{it.Org}' like '%'+OrgCode+'%'", connectionString);

			List<CallBackDTO> CallBackDTOs = new List<CallBackDTO>();
			var ids = "";
			if (ds.Tables.Count > 0)
			{
				DataTable dt = ds.Tables[0];
				if (dt != null && dt.Rows.Count > 0)
				{
					for (int i = 0; i < dt.Rows.Count; i++)
					{

						CallBackDTO dto = new CallBackDTO();
						dto.Pkid = Convert.ToInt64(dt.Rows[i]["MESPkid"].ToString());
						dto.DocNo = dt.Rows[i]["DocNo"].ToString();
						dto.Status = Convert.ToInt32(dt.Rows[i]["Status"].ToString());
						dto.Type = (int)Enum.Parse(typeof(CallBackType), dt.Rows[i]["RequireType"].ToString());
						dto.ErrorMessage = dt.Rows[i]["ErrorMessage"].ToString();


						CallBackDTOs.Add(dto);
						ids += dt.Rows[i]["id"].ToString() + ",";
					}

				}
			}

			if (CallBackDTOs.Count > 0)
			{
				var DTOsGroupByType = CallBackDTOs.GroupBy(m => m.Type).ToList();

				foreach (var dtos in DTOsGroupByType)
				{
					string errormsg = "";
					CallBackCommon CallBackCommon = new CallBackCommon();
					CallBackCommon.callBackType = dtos.FirstOrDefault().Type;
					List<CallBackInfo> callBackInfos = new List<CallBackInfo>();


					foreach (var dto in dtos)
					{
						CallBackInfo info = new CallBackInfo();
						info.Pkid = dto.Pkid;
						info.IsSuccess = dto.Status == 1 ? true : false;
						info.ERPBillno = dto.DocNo;
						callBackInfos.Add(info);
						errormsg += string.IsNullOrEmpty(dto.ErrorMessage) ? "" : ("Pkid:" + dto.Pkid + " ErrorMessage:" + dto.ErrorMessage + ";");
					}

					CallBackCommon.callBackInfos = callBackInfos;

					List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
					QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
					//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
					QuartzTaskInfoDTO.jobId = "CallBack_BatchData";
					QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(CallBackCommon);
					QuartzTaskInfoDTO.quartzStatus = 0;
					QuartzTaskInfoDTO.jobResult = errormsg;
					QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
					string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
					{
						userNo = "100",
						factoryId = it.Org,
						quartzTaskInfoDTOs = QuartzTaskInfoDTOs

					});
					//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
					var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{IsnJson}' where id ={rdid}";
					DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
					PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);
				}
				if (ids != "")
				{
					DbHelperSQL.ExecuteSql("update Inter_PullListBE set Status = 3 where id in (" + ids.Substring(0, ids.Length - 1) + ")", connectionString);
				}
			}

			result.msg = "下发成功";
			return result;
		}

		public class CreatePullListCallBackDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";
		}

		[HttpPost]
		public Result<string> CreateCompleteRptCallBack(CreateCompleteRptCallBackDTO it)
		{
			Result<string> result = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						result.code = 0;
						result.msg = "该token已失效";
						return result;
					}
				}
				else
				{
					result.code = 0;
					result.msg = "无效token";
					return result;
				}
			}
			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			if (string.IsNullOrEmpty(MESURL))
			{
				result.code = 0;
				result.msg = "未找到MES地址";
				return result;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'CreateCompleteRptCallBack', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);

			DataSet ds = DbHelperSQL.Query($"select * from Inter_CompRptBE where (Status = 1 or Status = 2) and   '{it.Org}' like '%'+OrgCode+'%'", connectionString);

			List<CallBackDTO> CallBackDTOs = new List<CallBackDTO>();
			var ids = "";
			if (ds.Tables.Count > 0)
			{
				DataTable dt = ds.Tables[0];
				if (dt != null && dt.Rows.Count > 0)
				{
					for (int i = 0; i < dt.Rows.Count; i++)
					{

						CallBackDTO dto = new CallBackDTO();
						dto.Pkid = Convert.ToInt64(dt.Rows[i]["MESPkid"].ToString());
						dto.DocNo = dt.Rows[i]["DocNo"].ToString();
						dto.Status = Convert.ToInt32(dt.Rows[i]["Status"].ToString());
						dto.Type = (int)CallBackType.完工入库;
						dto.ErrorMessage = dt.Rows[i]["ErrorMessage"].ToString();


						CallBackDTOs.Add(dto);
						ids += dt.Rows[i]["id"].ToString() + ",";
					}

				}
			}
			if (CallBackDTOs.Count > 0)
			{
				string errormsg = "";
				CallBackCommon CallBackCommon = new CallBackCommon();
				CallBackCommon.callBackType = (int)CallBackType.完工入库;
				List<CallBackInfo> callBackInfos = new List<CallBackInfo>();


				foreach (var dto in CallBackDTOs)
				{
					CallBackInfo info = new CallBackInfo();
					info.Pkid = dto.Pkid;
					info.IsSuccess = dto.Status == 1 ? true : false;
					info.ERPBillno = dto.DocNo;
					callBackInfos.Add(info);
					errormsg += string.IsNullOrEmpty(dto.ErrorMessage) ? "" : ("Pkid:" + dto.Pkid + " ErrorMessage:" + dto.ErrorMessage + ";");
				}

				CallBackCommon.callBackInfos = callBackInfos;

				List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
				QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
				//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
				QuartzTaskInfoDTO.jobId = "CallBack_BatchData";
				QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(CallBackCommon);
				QuartzTaskInfoDTO.quartzStatus = 0;
				QuartzTaskInfoDTO.jobResult = errormsg;
				QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
				string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
				{
					userNo = "100",
					factoryId = it.Org,
					quartzTaskInfoDTOs = QuartzTaskInfoDTOs

				});
				//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
				var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{IsnJson}' where id ={rdid}";
				DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
				var rtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);

				if (ids != "")
				{
					DbHelperSQL.ExecuteSql("update Inter_CompRptBE set Status = 3 where id in (" + ids.Substring(0, ids.Length - 1) + ")", connectionString);
				}
			}
			result.msg = "下发成功";
			return result;
		}

		public class CreateCompleteRptCallBackDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";
		}

		[HttpPost]
		public Result<string> CreateTransferDocAfterShipmentCallBack(CreateTransferDocAfterShipmentCallBackDTO it)
		{
			//DataSet ds = DbHelperSQL.Query("select * from Inter_TransferInBE where  CallBackType = 2 and (Status = 1 or Status = 2 )", connectionString);

			List<CallBackDTO> CallBackDTOs = new List<CallBackDTO>();

			Result<string> result = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						result.code = 0;
						result.msg = "该token已失效";
						return result;
					}
				}
				else
				{
					result.code = 0;
					result.msg = "无效token";
					return result;
				}
			}
			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			if (string.IsNullOrEmpty(MESURL))
			{
				result.code = 0;
				result.msg = "未找到MES地址";
				return result;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'CreateTransferDocAfterShipmentCallBack', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);

			DataSet ds2 = DbHelperSQL.Query($"select * from Inter_ShipBE where ( Status = 1 or Status = 2 )  and   '{it.Org}' like '%'+OrgCode+'%'", connectionString);
			var ids2 = "";
			if (ds2.Tables.Count > 0)
			{
				DataTable dt = ds2.Tables[0];
				if (dt != null && dt.Rows.Count > 0)
				{
					for (int i = 0; i < dt.Rows.Count; i++)
					{
						//CallBackDTO ck = CallBackDTOs.FirstOrDefault(m=>m.Pkid == Convert.ToInt64(dt.Rows[i]["Seller"].ToString()) && m.DocNo == dt.Rows[i]["DocNo"].ToString() &&)

						CallBackDTO dto = new CallBackDTO();
						dto.Pkid = Convert.ToInt64(dt.Rows[i]["Seller"].ToString());
						dto.DocNo = dt.Rows[i]["DocNo"].ToString();
						dto.Status = Convert.ToInt32(dt.Rows[i]["Status"].ToString());
						dto.Type = (int)CallBackType.销售出库凭证;
						dto.ErrorMessage = dt.Rows[i]["ErrorMessage"].ToString();


						CallBackDTOs.Add(dto);
						ids2 += dt.Rows[i]["id"].ToString() + ",";
					}

				}
			}

			if (CallBackDTOs.Count > 0)
			{
				string errormsg = "";
				CallBackCommon CallBackCommon = new CallBackCommon();
				CallBackCommon.callBackType = (int)CallBackType.销售出库凭证;
				List<CallBackInfo> callBackInfos = new List<CallBackInfo>();


				foreach (var dto in CallBackDTOs)
				{
					CallBackInfo info = new CallBackInfo();
					info.Pkid = dto.Pkid;
					info.IsSuccess = dto.Status == 1 ? true : false;
					info.ERPBillno = dto.DocNo;
					callBackInfos.Add(info);
					errormsg += string.IsNullOrEmpty(dto.ErrorMessage) ? "" : ("Pkid:" + dto.Pkid + " ErrorMessage:" + dto.ErrorMessage + ";");
				}

				CallBackCommon.callBackInfos = callBackInfos;

				List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
				QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
				//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
				QuartzTaskInfoDTO.jobId = "CallBack_BatchData";
				QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(CallBackCommon);
				QuartzTaskInfoDTO.quartzStatus = 0;
				QuartzTaskInfoDTO.jobResult = errormsg;
				QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
				string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
				{
					userNo = "100",
					factoryId = it.Org,
					quartzTaskInfoDTOs = QuartzTaskInfoDTOs

				});
				//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
				var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{IsnJson}' where id ={rdid}";
				DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
				PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);

				//if (ids != "")
				//{
				//	DbHelperSQL.ExecuteSql("update Inter_TransferInBE set Status = 3 where id in (" + ids.Substring(0, ids.Length - 1) + ")", connectionString);
				//}

				if (ids2 != "")
				{
					DbHelperSQL.ExecuteSql("update Inter_ShipBE set Status = 3 where id in (" + ids2.Substring(0, ids2.Length - 1) + ")", connectionString);
				}
			}
			result.msg = "下发成功";
			return result;
		}

		public class CreateTransferDocAfterShipmentCallBackDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";
		}


		[HttpPost]
		public Result<string> CreateTransferDocAfterFixCallBack(CreateTransferDocAfterFixCallBackDTO it)
		{
			Result<string> result = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						result.code = 0;
						result.msg = "该token已失效";
						return result;
					}
				}
				else
				{
					result.code = 0;
					result.msg = "无效token";
					return result;
				}
			}
			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			if (string.IsNullOrEmpty(MESURL))
			{
				result.code = 0;
				result.msg = "未找到MES地址";
				return result;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'CreateTransferDocAfterFixCallBack', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);

			DataSet ds = DbHelperSQL.Query($"select * from Inter_NewTransferInBE where ( Status = 1 or Status = 2 )  and   '{it.Org}' like '%'+OrgCode+'%'", connectionString);

			List<CallBackDTO> CallBackDTOs = new List<CallBackDTO>();
			var ids = "";
			if (ds.Tables.Count > 0)
			{
				DataTable dt = ds.Tables[0];
				if (dt != null && dt.Rows.Count > 0)
				{
					for (int i = 0; i < dt.Rows.Count; i++)
					{

						CallBackDTO dto = new CallBackDTO();
						dto.Pkid = Convert.ToInt64(dt.Rows[i]["MESPkid"].ToString());
						dto.DocNo = dt.Rows[i]["DocNo"].ToString();
						dto.Status = Convert.ToInt32(dt.Rows[i]["Status"].ToString());
						dto.Type = (int)CallBackType.产品合格与不合格调拨;
						dto.ErrorMessage = dt.Rows[i]["ErrorMessage"].ToString();


						CallBackDTOs.Add(dto);
						ids += dt.Rows[i]["id"].ToString() + ",";
					}

				}
			}
			if (CallBackDTOs.Count > 0)
			{
				string errormsg = "";
				CallBackCommon CallBackCommon = new CallBackCommon();
				CallBackCommon.callBackType = (int)CallBackType.产品合格与不合格调拨;
				List<CallBackInfo> callBackInfos = new List<CallBackInfo>();


				foreach (var dto in CallBackDTOs)
				{
					CallBackInfo info = new CallBackInfo();
					info.Pkid = dto.Pkid;
					info.IsSuccess = dto.Status == 1 ? true : false;
					info.ERPBillno = dto.DocNo;
					callBackInfos.Add(info);
					errormsg += string.IsNullOrEmpty(dto.ErrorMessage) ? "" : ("Pkid:" + dto.Pkid + " ErrorMessage:" + dto.ErrorMessage + ";");
				}

				CallBackCommon.callBackInfos = callBackInfos;

				List<QuartzTaskInfoDTO> QuartzTaskInfoDTOs = new List<QuartzTaskInfoDTO>();
				QuartzTaskInfoDTO QuartzTaskInfoDTO = new QuartzTaskInfoDTO();
				//QuartzTaskInfoDTO.jobPkid = 4127739008581701;
				QuartzTaskInfoDTO.jobId = "CallBack_BatchData";
				QuartzTaskInfoDTO.jobMsg = JsonConvert.SerializeObject(CallBackCommon);
				QuartzTaskInfoDTO.quartzStatus = 0;
				QuartzTaskInfoDTO.jobResult = errormsg;
				QuartzTaskInfoDTOs.Add(QuartzTaskInfoDTO);
				string IsnJson = JsonConvert.SerializeObject(new RequestQuartzTasksInfoDto
				{
					userNo = "100",
					factoryId = it.Org,
					quartzTaskInfoDTOs = QuartzTaskInfoDTOs

				});
				//string MESURL = System.Configuration.ConfigurationManager.AppSettings[it.Org].ToString();
				var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{IsnJson}' where id ={rdid}";
				DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
				PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info-ins", IsnJson);

				if (ids != "")
				{
					DbHelperSQL.ExecuteSql("update Inter_NewTransferInBE set Status = 3 where id in (" + ids.Substring(0, ids.Length - 1) + ")", connectionString);
				}
			}
			result.msg = "下发成功";
			return result;

		}

		public class CreateTransferDocAfterFixCallBackDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";
		}

		public static long GuidToLongID()
		{
			byte[] buffer = Guid.NewGuid().ToByteArray();
			return BitConverter.ToInt64(buffer, 0);
		}

		public void WriteLog(string msg, string doctype)
		{
			try
			{
				string ip;
				ip = "local";
				string logFile = doctype;
				System.IO.StreamWriter sw = System.IO.File.AppendText(
					AppDomain.CurrentDomain.BaseDirectory + @"log\" + "debug_" + logFile + "_" +
					DateTime.Now.ToString("yyyyMMddHH") + ".Log"
					);
				sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + "from:" + ip + " " + msg);
				sw.Close();
			}
			catch
			{ }
		}

		public class Result<T>
		{

			public int code { get; set; } = 1;


			public T data { get; set; }

			public string msg { get; set; } = "";
		}


		/// <summary>
		/// DES数据解密
		/// </summary>
		/// <param name="targetValue"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string Decrypt(string targetValue, string key)
		{
			if (string.IsNullOrEmpty(targetValue))
			{
				return string.Empty;
			}
			// 定义DES加密对象
			var des = new DESCryptoServiceProvider();
			int len = targetValue.Length / 2;
			var inputByteArray = new byte[len];
			int x, i;
			for (x = 0; x < len; x++)
			{
				i = Convert.ToInt32(targetValue.Substring(x * 2, 2), 16);
				inputByteArray[x] = (byte)i;
			}
			// 通过两次哈希密码设置对称算法的初始化向量   
			des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
													(FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").
														Substring(0, 8), "sha1").Substring(0, 8));
			// 通过两次哈希密码设置算法的机密密钥   
			des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
													(FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")
														.Substring(0, 8), "md5").Substring(0, 8));
			// 定义内存流
			var ms = new MemoryStream();
			// 定义加密流
			var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
			cs.Write(inputByteArray, 0, inputByteArray.Length);
			cs.FlushFinalBlock();
			return Encoding.Default.GetString(ms.ToArray());
		}

	}



}
